package com.hbnu.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author kittychen
 * @since 2025-10-28 19:02
 */
public class UdpSendDemo01 {

    public static void main(String[] args) {
        DatagramSocket ds = null;
        try {
            // 1、创建Socket
            ds = new DatagramSocket(6666);

            // 2、准备数据，并将数据封装到数据报包中
            String str = "hello";
            byte[] bytes = str.getBytes();
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length,
                    InetAddress.getByName("127.0.0.1"), 8888);

            // 3、发送数据
            ds.send(dp);

            System.out.println("数据发送成功！！！");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 4、关闭资源
            if (ds != null) {
                ds.close();
            }
        }
    }
}
